package yanyan.com.tochar.funsactivity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.PixelFormat;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.Icon;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RemoteViews;
import android.widget.TextView;

import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.entity.LocalMedia;

import java.util.List;
import java.util.Random;

import androidx.annotation.RequiresApi;
import androidx.core.app.NotificationCompat;
import okhttp3.OkHttpClient;
import yanyan.com.tochar.R;
import yanyan.com.tochar.adpter.DiaLogListAdapter;
import yanyan.com.tochar.dialog.ListDialog;
import yanyan.com.tochar.utils.CoreUtil;
import yanyan.com.tochar.utils.EmptyUtils;
import yanyan.com.tochar.utils.PictureSelectUtil;
import yanyan.com.tochar.utils.ToastUtil;

/**
 * 自定义通知
 */
public class FunsNoticeActivity extends Activity {
    private EditText titleEd,textEd,levlelEd;
    private Bitmap iconBitmap;
    private Button selectBtn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_funs_notice);
        titleEd=findViewById(R.id.notice_title);
        textEd=findViewById(R.id.notice_text);
        levlelEd=findViewById(R.id.notice_level);
        selectBtn=findViewById(R.id.notice_select);

        //统计各功能
        CoreUtil.statisticalFuns(this,"funs_notes");

    }



    public void startNotice(View view){
        if(Build.VERSION.SDK_INT >= 23){
            String title=titleEd.getText().toString();
            String text=textEd.getText().toString();
            String levelStr=levlelEd.getText().toString();
            if(EmptyUtils.isEmpty(iconBitmap)){
                ToastUtil.showLongToast(this,"请选择要模拟通知的应用");
                return;
            }
            if(EmptyUtils.isEmpty(title)){
                ToastUtil.showLongToast(this,"请输入标题");
                return;
            }
            if(EmptyUtils.isEmpty(levelStr)){
                ToastUtil.showLongToast(this,"请输入延迟时间");
                return;
            }
            if(EmptyUtils.isEmpty(text)){
                ToastUtil.showLongToast(this,"请输入通知内容");
                return;
            }


            int level=Integer.parseInt(levelStr);
            ToastUtil.showLongToast(this,"通知将于"+level+"秒后发送");
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(level*1000);
                        createNotice(iconBitmap,title,text);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }).start();


//            createNotice();

        }else {
            ToastUtil.showShotToast(this,"android版本太低，无法使用该功能");
        }

    }


//    @RequiresApi(api = Build.VERSION_CODES.M)
//    private void createNotice(){
//        //1.获取系统通知的管理者
//        NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
//        //2.初始化一个notification的对象
//        Notification.Builder mBuilder =new Notification.Builder(this);
//        //android 8.0 适配     需要配置 通知渠道NotificationChannel
//        NotificationChannel b;
//        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
//            int importance = NotificationManager.IMPORTANCE_MAX;
//            b = new NotificationChannel("1","哈哈哈",importance);
//            nm.createNotificationChannel(b);
//            mBuilder.setChannelId("1");
//        }
//        //添加自定义视图  activity_notification
////        RemoteViews mRemoteViews = new RemoteViews(getPackageName(),R.layout.item_notice);
////        //主要设置setContent参数  其他参数 按需设置
////        mBuilder.setContent(mRemoteViews);
//        Icon icon=Icon.createWithBitmap(BitmapFactory.decodeResource(getResources(),R.mipmap.funs_code));
//        mBuilder.setSmallIcon(icon);
//        mBuilder.setOngoing(true);
//        mBuilder.setLargeIcon(icon);
//        mBuilder.setAutoCancel(true);
//        mBuilder.setContentTitle("666666");
//        mBuilder.setContentText("9999999999999999999999");
//        //更新Notification
//        nm.notify(1,mBuilder.build());
//    }



    @RequiresApi(api = Build.VERSION_CODES.M)
    private void createNotice(Bitmap ico, String title, String text){
        //创建通知管理类
        NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        Icon icon=Icon.createWithBitmap(ico);
        Random random=new Random();
        if(Build.VERSION.SDK_INT >= 26) {
            //当sdk版本大于26
            String id = "channel_1";
            String description = "143";
            int importance = NotificationManager.IMPORTANCE_HIGH;
            NotificationChannel channel = new NotificationChannel(id, description, importance);
            manager.createNotificationChannel(channel);
            Notification notification = new Notification.Builder(FunsNoticeActivity.this, id)
                    .setCategory(Notification.CATEGORY_MESSAGE)
                    .setSmallIcon(icon)
                    .setContentTitle(title)
                    .setContentText(text)
                    .setContentIntent(null)
                    .setAutoCancel(true)
                    .setShowWhen(true)
                    .setLargeIcon(icon)
                    .build();
            manager.notify(random.nextInt(),notification);
        }
        else {
            //当sdk版本小于26
            Notification notification = new NotificationCompat.Builder(FunsNoticeActivity.this,"111")
                    .setCategory(Notification.CATEGORY_MESSAGE)
                    .setContentTitle(title)
                    .setContentText(text)
                    .setContentIntent(null)
                    .setShowWhen(true)
                    .setLargeIcon(iconBitmap)
                    .build();
            manager.notify(random.nextInt(),notification);

        }
    }

    /**
     * 选择app
     */
    private DiaLogListAdapter diaLogListAdapter;
    public void selectApp(View view){
        List<PackageInfo> installedPackages = getPackageManager().getInstalledPackages(0);
        ListDialog dialog=new ListDialog(this, "选择应用图标", installedPackages, new ListDialog.Selected() {
            @Override
            public void getAppInfo(int position) {
              ApplicationInfo applicationInfo=  installedPackages.get(position).applicationInfo;
                String appName= applicationInfo.loadLabel(getPackageManager()).toString();
                Drawable appIcon = applicationInfo.loadIcon(getPackageManager());
                iconBitmap= drawableToBitmap(appIcon);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                       titleEd.setText(appName);
                       selectBtn.setText("已选："+appName);
                    }
                });
            }
        });

        dialog.show();
    }

    /**
     * 选择图片
     * @param view
     */
    public void selectIco(View view){
        PictureSelectUtil.selectPohto(this,3306);
    }

    /**
     * Drawable转换成一个Bitmap
     *
     * @param drawable drawable对象
     * @return
     */
    public  Bitmap drawableToBitmap(Drawable drawable) {
        Bitmap bitmap = Bitmap.createBitmap( drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(),
                drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565);
        Canvas canvas = new Canvas(bitmap);
        drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
        drawable.draw(canvas);
        return bitmap;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode==RESULT_OK){
            List<LocalMedia> localMedias = PictureSelector.obtainMultipleResult(data);
            String path="";
            if(localMedias!=null && localMedias.size()>0){
                LocalMedia localMedia = localMedias.get(0);
                if(CoreUtil.isAndroidQ()){
                    path=localMedia.getAndroidQToPath();
                }else {
                    path= localMedia.getPath();
                }
                iconBitmap = PictureSelectUtil.getBitmap(path);

            }
        }else {
            ToastUtil.showShotToast(this,"图片选择失败");
        }
    }

}
